package com.farmer.knowledge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.farmer.common.entity.AgriKnowledge;
import com.farmer.common.result.Result;
import com.farmer.knowledge.mapper.KnowledgeMapper;
import com.farmer.knowledge.service.KnowledgeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 农技知识库服务实现类
 */
@Slf4j
@Service
public class KnowledgeServiceImpl implements KnowledgeService {

    @Autowired
    private KnowledgeMapper knowledgeMapper;

    @Override
    public Result<?> getKnowledgeList(Integer pageNum, Integer pageSize, String category, String keyword) {
        try {
            Page<AgriKnowledge> page = new Page<>(pageNum, pageSize);
            QueryWrapper<AgriKnowledge> queryWrapper = new QueryWrapper<>();
            
            // 只查询已发布的内容
            queryWrapper.eq("status", 1);
            
            // 分类过滤
            if (StringUtils.hasText(category)) {
                queryWrapper.eq("category", category);
            }
            
            // 关键词搜索
            if (StringUtils.hasText(keyword)) {
                queryWrapper.like("title", keyword)
                           .or()
                           .like("content", keyword)
                           .or()
                           .like("tags", keyword);
            }
            
            // 按发布时间倒序，推荐内容优先
            queryWrapper.orderByDesc("is_featured")
                       .orderByDesc("publish_time");
            
            Page<AgriKnowledge> knowledgePage = knowledgeMapper.selectPage(page, queryWrapper);
            
            Map<String, Object> result = new HashMap<>();
            result.put("records", knowledgePage.getRecords());
            result.put("total", knowledgePage.getTotal());
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            
            return Result.success("获取知识库列表成功", result);
        } catch (Exception e) {
            log.error("获取知识库列表失败：{}", e.getMessage(), e);
            return Result.error("获取知识库列表失败");
        }
    }

    @Override
    public Result<?> getKnowledgeById(Long id) {
        try {
            if (id == null) {
                return Result.error("知识ID不能为空");
            }

            AgriKnowledge knowledge = knowledgeMapper.selectById(id);
            if (knowledge == null) {
                return Result.error("知识不存在");
            }

            return Result.success("获取知识详情成功", knowledge);
        } catch (Exception e) {
            log.error("获取知识详情失败：{}", e.getMessage(), e);
            return Result.error("获取知识详情失败");
        }
    }

    @Override
    public Result<?> addKnowledge(AgriKnowledge knowledge) {
        try {
            if (knowledge == null) {
                return Result.error("知识内容不能为空");
            }

            // 设置默认值
            knowledge.setViewCount(0);
            knowledge.setLikeCount(0);
            knowledge.setIsFeatured(0);
            knowledge.setStatus(1); // 默认为发布状态
            knowledge.setCreateTime(LocalDateTime.now());
            knowledge.setUpdateTime(LocalDateTime.now());

            int result = knowledgeMapper.insert(knowledge);
            if (result > 0) {
                log.info("添加知识成功，知识ID：{}", knowledge.getId());
                return Result.success("添加知识成功", knowledge);
            } else {
                return Result.error("添加知识失败");
            }
        } catch (Exception e) {
            log.error("添加知识失败：{}", e.getMessage(), e);
            return Result.error("添加知识失败");
        }
    }

    @Override
    public Result<?> updateKnowledge(AgriKnowledge knowledge) {
        try {
            if (knowledge == null || knowledge.getId() == null) {
                return Result.error("知识信息不能为空");
            }

            // 检查知识是否存在
            AgriKnowledge existKnowledge = knowledgeMapper.selectById(knowledge.getId());
            if (existKnowledge == null) {
                return Result.error("知识不存在");
            }

            knowledge.setUpdateTime(LocalDateTime.now());

            int result = knowledgeMapper.updateById(knowledge);
            if (result > 0) {
                log.info("更新知识成功，知识ID：{}", knowledge.getId());
                return Result.success("更新知识成功");
            } else {
                return Result.error("更新知识失败");
            }
        } catch (Exception e) {
            log.error("更新知识失败：{}", e.getMessage(), e);
            return Result.error("更新知识失败");
        }
    }

    @Override
    public Result<?> deleteKnowledge(Long id) {
        try {
            if (id == null) {
                return Result.error("知识ID不能为空");
            }

            int result = knowledgeMapper.deleteById(id);
            if (result > 0) {
                log.info("删除知识成功，知识ID：{}", id);
                return Result.success("删除知识成功");
            } else {
                return Result.error("删除知识失败");
            }
        } catch (Exception e) {
            log.error("删除知识失败：{}", e.getMessage(), e);
            return Result.error("删除知识失败");
        }
    }

    @Override
    public Result<?> getFeaturedKnowledgeList(Integer limit) {
        try {
            QueryWrapper<AgriKnowledge> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 1)
                       .eq("is_featured", 1)
                       .orderByDesc("publish_time")
                       .last("LIMIT " + (limit != null ? limit : 10));
            
            List<AgriKnowledge> knowledgeList = knowledgeMapper.selectList(queryWrapper);
            
            return Result.success("获取推荐知识列表成功", knowledgeList);
        } catch (Exception e) {
            log.error("获取推荐知识列表失败：{}", e.getMessage(), e);
            return Result.error("获取推荐知识列表失败");
        }
    }

    @Override
    public Result<?> getCategoryList() {
        try {
            QueryWrapper<AgriKnowledge> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("DISTINCT category")
                       .eq("status", 1)
                       .isNotNull("category");
            
            List<AgriKnowledge> categoryList = knowledgeMapper.selectList(queryWrapper);
            
            // 提取分类名称
            List<String> categories = new ArrayList<>();
            for (AgriKnowledge knowledge : categoryList) {
                if (StringUtils.hasText(knowledge.getCategory())) {
                    categories.add(knowledge.getCategory());
                }
            }
            
            return Result.success("获取知识分类列表成功", categories);
        } catch (Exception e) {
            log.error("获取知识分类列表失败：{}", e.getMessage(), e);
            return Result.error("获取知识分类列表失败");
        }
    }

    @Override
    public Result<?> increaseViewCount(Long id) {
        try {
            if (id == null) {
                return Result.error("知识ID不能为空");
            }

            AgriKnowledge knowledge = knowledgeMapper.selectById(id);
            if (knowledge == null) {
                return Result.error("知识不存在");
            }

            knowledge.setViewCount(knowledge.getViewCount() + 1);
            knowledge.setUpdateTime(LocalDateTime.now());

            int result = knowledgeMapper.updateById(knowledge);
            if (result > 0) {
                return Result.success("更新浏览次数成功");
            } else {
                return Result.error("更新浏览次数失败");
            }
        } catch (Exception e) {
            log.error("更新浏览次数失败：{}", e.getMessage(), e);
            return Result.error("更新浏览次数失败");
        }
    }

    @Override
    public Result<?> toggleLike(Long id, Boolean isLike) {
        try {
            if (id == null) {
                return Result.error("知识ID不能为空");
            }

            AgriKnowledge knowledge = knowledgeMapper.selectById(id);
            if (knowledge == null) {
                return Result.error("知识不存在");
            }

            int currentLikeCount = knowledge.getLikeCount();
            if (isLike) {
                knowledge.setLikeCount(currentLikeCount + 1);
            } else {
                knowledge.setLikeCount(Math.max(0, currentLikeCount - 1));
            }
            knowledge.setUpdateTime(LocalDateTime.now());

            int result = knowledgeMapper.updateById(knowledge);
            if (result > 0) {
                return Result.success(isLike ? "点赞成功" : "取消点赞成功");
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            log.error("点赞操作失败：{}", e.getMessage(), e);
            return Result.error("点赞操作失败");
        }
    }

    @Override
    public Result<?> updateStatus(Long id, Integer status) {
        try {
            if (id == null || status == null) {
                return Result.error("参数不能为空");
            }

            AgriKnowledge knowledge = knowledgeMapper.selectById(id);
            if (knowledge == null) {
                return Result.error("知识不存在");
            }

            knowledge.setStatus(status);
            if (status == 1) {
                knowledge.setPublishTime(LocalDateTime.now());
            }
            knowledge.setUpdateTime(LocalDateTime.now());

            int result = knowledgeMapper.updateById(knowledge);
            if (result > 0) {
                String message = status == 1 ? "发布成功" : "下架成功";
                log.info("{}，知识ID：{}", message, id);
                return Result.success(message);
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            log.error("更新知识状态失败：{}", e.getMessage(), e);
            return Result.error("更新知识状态失败");
        }
    }
} 